using FileTransferDesktop.Services;
using Wpf.Ui.Abstractions.Controls;

namespace FileTransferDesktop.ViewModels.Dialogs;

public partial class AuthDialogViewModel(IAuthenticationService authenticationService)
    : ObservableObject,
        INavigationAware
{
    private bool _isInitialized = false;

    // 当前模式 - true为注册模式，false为登录模式
    [ObservableProperty]
    private bool _isRegisterMode = false;

    // 登录字段
    [ObservableProperty]
    private string _loginUsername = string.Empty;

    [ObservableProperty]
    private string _loginPassword = string.Empty;

    [ObservableProperty]
    private bool _rememberMe = false;

    // 注册字段
    [ObservableProperty]
    private string _registerUsername = string.Empty;

    [ObservableProperty]
    private string _registerEmail = string.Empty;

    [ObservableProperty]
    private string _registerPassword = string.Empty;

    [ObservableProperty]
    private string _confirmPassword = string.Empty;

    [ObservableProperty]
    private string _displayName = string.Empty;

    // 共同字段
    [ObservableProperty]
    private bool _isLoading = false;

    [ObservableProperty]
    private string _errorMessage = string.Empty;

    [ObservableProperty]
    private bool _hasError = false;

    public Task OnNavigatedToAsync()
    {
        if (!_isInitialized)
            InitializeViewModel();

        return Task.CompletedTask;
    }

    public Task OnNavigatedFromAsync() => Task.CompletedTask;

    private void InitializeViewModel()
    {
        LoadLastLoginUser();
        _isInitialized = true;
    }

    [RelayCommand]
    private void SwitchToLogin()
    {
        IsRegisterMode = false;
        ClearErrors();
    }

    [RelayCommand]
    private void SwitchToRegister()
    {
        IsRegisterMode = true;
        ClearErrors();
    }

    [RelayCommand]
    private async Task LoginAsync()
    {
        if (IsLoading)
            return;

        try
        {
            ClearErrors();
            IsLoading = true;

            // 验证输入
            if (string.IsNullOrWhiteSpace(LoginUsername))
            {
                ShowError("请输入用户名或邮箱");
                return;
            }

            if (string.IsNullOrWhiteSpace(LoginPassword))
            {
                ShowError("请输入密码");
                return;
            }

            // 调用认证服务
            await authenticationService.LoginAsync(LoginUsername, LoginPassword, RememberMe);
        }
        catch (Exception ex)
        {
            ShowError($"登录失败: {ex.Message}");
        }
        finally
        {
            IsLoading = false;
        }
    }

    [RelayCommand]
    private async Task RegisterAsync()
    {
        if (IsLoading)
            return;

        try
        {
            ClearErrors();
            IsLoading = true;

            // 验证输入
            if (!ValidateRegisterForm())
                return;

            // 调用认证服务
            await authenticationService.RegisterAsync(
                RegisterUsername,
                RegisterEmail,
                RegisterPassword,
                string.IsNullOrWhiteSpace(DisplayName) ? RegisterUsername : DisplayName
            );

            // 注册成功，切换到登录模式并预填用户名
            LoginUsername = RegisterUsername;
            IsRegisterMode = false;
            ShowSuccess("注册成功！请使用新账户登录。");
        }
        catch (Exception ex)
        {
            ShowError($"注册失败: {ex.Message}");
        }
        finally
        {
            IsLoading = false;
        }
    }

    private bool ValidateRegisterForm()
    {
        if (string.IsNullOrWhiteSpace(RegisterUsername))
        {
            ShowError("请输入用户名");
            return false;
        }

        if (RegisterUsername.Length < 3 || RegisterUsername.Length > 50)
        {
            ShowError("用户名长度必须在3-50个字符之间");
            return false;
        }

        if (string.IsNullOrWhiteSpace(RegisterEmail))
        {
            ShowError("请输入邮箱地址");
            return false;
        }

        if (!IsValidEmail(RegisterEmail))
        {
            ShowError("请输入有效的邮箱地址");
            return false;
        }

        if (string.IsNullOrWhiteSpace(RegisterPassword))
        {
            ShowError("请输入密码");
            return false;
        }

        if (RegisterPassword.Length < 6 || RegisterPassword.Length > 128)
        {
            ShowError("密码长度必须在6-128个字符之间");
            return false;
        }

        if (RegisterPassword != ConfirmPassword)
        {
            ShowError("两次输入的密码不一致");
            return false;
        }

        return true;
    }

    private static bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }

    private void ShowError(string message)
    {
        ErrorMessage = message;
        HasError = true;
    }

    private void ShowSuccess(string message)
    {
        // 这里可以显示成功消息，暂时清除错误
        ClearErrors();
    }

    private void ClearErrors()
    {
        HasError = false;
        ErrorMessage = string.Empty;
    }

    private void ClearForm()
    {
        // 清空登录表单
        LoginUsername = string.Empty;
        LoginPassword = string.Empty;
        RememberMe = true;

        // 清空注册表单
        RegisterUsername = string.Empty;
        RegisterEmail = string.Empty;
        RegisterPassword = string.Empty;
        ConfirmPassword = string.Empty;
        DisplayName = string.Empty;

        // 清空状态
        IsLoading = false;
        ClearErrors();
    }

    private void LoadLastLoginUser()
    {
        ClearForm();

        // 尝试加载最后登录的用户名
        var lastLoginUser = authenticationService.GetLastLoginUser();
        if (!string.IsNullOrEmpty(lastLoginUser))
        {
            LoginUsername = lastLoginUser;
        }
        else
        {
#if DEBUG
            // 只有在没有保存的用户名时才使用测试用户名
            LoginUsername = "testuser";
            LoginPassword = "test123";
#endif
        }
    }

    public void SetMode(bool isRegisterMode)
    {
        IsRegisterMode = isRegisterMode;
        ClearErrors();
    }
}
